package cn.com.oyat.idea.util;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;

/**
 * 雪花算法工具类
 *
 * @author cs
 * @date 2021/9/27
 */
public class SnowFlakeUtil {

    private Snowflake snowflake;

    /**
     *
     * @param machineId 终端ID
     * @param dataCenterId 数据中心ID
     */
    public SnowFlakeUtil(long machineId, long dataCenterId) {
    	if(machineId== 0 || dataCenterId == 0) {
    		throw new RuntimeException("不允许终端ID和数据中心ID都为0");
    	}
        snowflake = IdUtil.getSnowflake(machineId, dataCenterId);
    }

    /**
     * 成员类，SnowFlakeUtil的实例对象的保存域
     */
    private static class IdGenHolder {
        private static final SnowFlakeUtil instance = new SnowFlakeUtil();
    }

    /**
     * 外部调用获取SnowFlakeUtil的实例对象，确保不可变
     */
    public static SnowFlakeUtil get() {
        return IdGenHolder.instance;
    }

    /**
     * 初始化构造，无参构造有参函数，默认节点都是0
     */
    private SnowFlakeUtil() {
        snowflake = IdUtil.getSnowflake(0L, 0L);
    }

    public synchronized long id(){
        return snowflake.nextId();
    }

    public static Long getId() {
        return SnowFlakeUtil.get().id();
    }

    public static String getIdOfStr() {
        return String.valueOf(SnowFlakeUtil.get().id());
    }

}
